<?php
/**
 * Created by PhpStorm.
 * User: liuxin
 * Date: 2017/12/29
 * Time: 上午1:42
 */

namespace common\components;

use backend\models\UploadExcel;
use GuzzleHttp\Client;
use Yii;
use yii\base\ErrorException;
use yii\base\InvalidValueException;
use yii\web\UploadedFile;

class Helper
{
    /**
     * 微信服务器curl请求专用
     * @param $request_url
     * @return mixed
     */
    public static function weChatCurl($request_url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $request_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    public static function  rePostStr($data,$sign){
        ksort($data);
        $post_str = '';
        foreach($data as $key=>$value){
            $post_str .=$key.'='.$value.'&';
        }
        if($post_str){
            $post_str = substr($post_str,0,-1);
        }
        $sign = md5($post_str.$sign);
        $post_str = $post_str.'&sign='.$sign;
        return $post_str;
    }

    public static function buildQuery($array){
        $str = '';
        foreach($array as $key => $val){
            $str .="{$key}={$val}&";
        }
        return trim($str,'&');
    }

    public static function curl($url, $post_str)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_str);
        curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)");
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    /**
     * @param $text
     * @return mixed
     */
    public static function response($text)
    {
        return json_decode($text, true);
    }

    public static function errorHandle($ErrorMessage){
        $error = "";
        if(!empty($ErrorMessage)){
            $error = array_pop($ErrorMessage);
        }
        return $error;
    }

    public static function downloadExcelTmp($name) {
            $path = 'uploads/template/'.$name.'.xlsx'; //文件名
            header('Content-type: application/octet-stream');
            header("Accept-Ranges: bytes");
            //下载显示的名字
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename='.$name.'.xlsx');
            header('Content-Transfer-Encoding: binary');
            header('Expires: 0');
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
            header('Pragma: public');
            header('Content-Length: ' . filesize($path));
            ob_clean();
            flush();
            echo readfile($path);
    }

    /**
     * 读取excel文件内容
     * @return bool
     */
    public static function read($file){
        $uploadType = substr(strrchr($file, '.'), 1);
        switch ($uploadType){
            case 'xlsx':
                $objReader =new \PHPExcel_Reader_Excel2007();
                break;
            case 'xls':
                $objReader =new \PHPExcel_Reader_Excel5();
                break;
            default:
                return true;
        }
        $objPHPExcel = $objReader->load($file);
        $objWorksheet = $objPHPExcel->getSheet(0);
        $highestRow = $objWorksheet->getHighestRow();//最大行数，为数字
        $highestColumn = $objWorksheet->getHighestColumn();//最大列数 为字母
        $highestColumnIndex = \PHPExcel_Cell::columnIndexFromString($highestColumn); //将字母变为数字

        $tableData = [];
        for($row = 1;$row<=$highestRow;$row++){
            for($col=0;$col< $highestColumnIndex;$col++){
                $tableData[$row][$col] = $objWorksheet->getCellByColumnAndRow($col,$row)->getValue();
            }
        }
        return $tableData;
    }

    public static function upload ($field ='file')
    {
        $model = new UploadExcel();
        if (Yii::$app->request->isPost) {
            $model->$field = UploadedFile::getInstance($model, $field);
            if(!empty($model->$field)){
                $uploadType = substr(strrchr($model->$field->name, '.'), 1);
            }else{
                echo "sorry！出错了！";exit;
            }
            $uploadUrl      = "public/uploads/ntmp/"."$uploadType"."/".date("Ymd");
            $savePath       = $uploadUrl;
            if (!is_dir($savePath))
                mkdir($savePath,0777,true);
            if ($model->validate()) {
                //文件名
                $fileName = date("HiiHsHis"). "." . $model->$field->extension;
                $dir = $savePath."/". $fileName;
                $model->$field->saveAs($dir);
                return $uploadUrl.'/'.$fileName;
            }

        }
    }

    public static function get_client_ip()
    {
        if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
            $ip = getenv("HTTP_CLIENT_IP");
        else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
            $ip = getenv("REMOTE_ADDR");
        else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
            $ip = $_SERVER['REMOTE_ADDR'];
        else
            $ip = "unknown";
        return ($ip);
    }

    public static function userClientServerIpIsAllowed()
    {

        if (!YII_DEBUG) {
            $server_ip = self::get_client_ip();
            $limited_ip_list = Yii::$app->params['is_allow_ips'];
            if (!in_array($server_ip, $limited_ip_list)) {
                $server_ip_header = substr($server_ip, 0, strrpos($server_ip, '.'));
                $server_ip_last = substr($server_ip, strrpos($server_ip, '.') + 1);
                if ($server_ip_header == $limited_ip_list['network']['0'] && ($server_ip_last >= 1 || $server_ip_last <= 127)) {
                    return true;
                }
                return false;
            }
            return true;
        }
        return true;
    }

    public static function parseCheckSign()
    {
        $postDataArr = Yii::$app->request->post();
        $_sign = $postDataArr['sign'];
        unset($postDataArr['sign']);
        ksort($postDataArr);
        $org_str = '';
        foreach ($postDataArr as $key => $value) {
            if ($key == 'team_name'){
                Yii::info($value,'app_login');
                $org_str .= empty($org_str) ? $key . '=' . urlencode($value) : '&' . $key . '=' . urlencode($value);
            }else{
                $org_str .= empty($org_str) ? $key . '=' . $value : '&' . $key . '=' . $value;
            }
        }
        if (md5($org_str . Yii::$app->params['open_sign_key']) !== $_sign) {

            return false;
        }
        return true;
    }

    /**
     * @return string
     * 生成随机串，防CSRF攻击
     */
    public static function createState($code)
    {
        $state = md5(uniqid(rand(), true));
        $redis = Factory::Redis();
        $redis->zadd('oauth_state', time(), $code . $state);
        return $state;
    }

    public static function CreateExpireTime($time)
    {
        return mt_rand($time, $time + 2 * 24 * 60 * 60);
    }

    public static function generate_password($length = 6)
    {
        // 密码字符集，可任意添加你需要的字符
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_ []{}<>~`+=,.;:/?|';
        $username = '';
        for ($i = 0; $i < $length; $i++) {
            $username .= $chars[mt_rand(0, strlen($chars) - 1)];
        }
        return $username;
    }

    public static function create_union_id($prefix = null)
    {
        return $prefix . md5(uniqid(md5(microtime(true)), true));
    }

    public static function generate_username($length = 6)
    {
        // 密码字符集，可任意添加你需要的字符
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $username = '';
        for ($i = 0; $i < $length; $i++) {
            $username .= $chars[mt_rand(0, strlen($chars) - 1)];
        }
        return $username;
    }

    public static function des_decrypt($str, $key)
    {
        $str = mcrypt_decrypt(MCRYPT_DES, $key, $str, MCRYPT_MODE_ECB);
        $len = strlen($str);
        $pad = ord($str[$len - 1]);
        return substr($str, 0, $len - $pad);
    }


    /**
     * 接口请求post
     * @param string $scheme 地址路径
     * @param array $encryptData 加密参数
     * @param array $data 非加密参数
     * @return array|mixed
     */
    public static function wechatHttpPost($scheme = '', array $encryptData, array $data)
    {
        //open_id 必须填写
        if (empty($encryptData['open_id'])) {
            return ['code' => -1, 'message' => 'not open_id'];
        }

        $str = Rsa::encrypt(json_encode($encryptData));
        if (!empty($str)) {
            $params['attention-data'] = $str;
            $params = array_merge($params, $data);
            //过滤加密参数对应的key
            $params = array_diff_key($params, array_intersect_key($params, $encryptData));
            $sign = md5(http_build_query($params) . Yii::$app->params['open_sign_key']);
            $params['sign'] = $sign;

            $client = new Client([
                'base_uri' => Yii::$app->params['api_base_uri'],
            ]);

            $response = $client->post($scheme, [
                'http_errors' => false,
                'form_params' => $params,
            ]);

            $content = $response->getBody();

            if (!empty($content)) {
                return json_decode($content, true);
            }
        }

        return ['code' => -1, 'message' => 'rsa encrypt error'];
    }

    /**
     * 接口请求post
     * @param string $scheme 地址路径
     * @param array $data 参数
     * @return array|mixed
     */
    public static function httpPost($scheme = '', array $params = [])
    {
        ksort($params);
        $sign = md5(static::httpBulidQuery($params) . Yii::$app->params['open_sign_key']);
        $params['sign'] = $sign;

        $client = new Client([
            'base_uri' => Yii::$app->params['api_base_uri'],
        ]);

        $response = $client->post($scheme, [
            'http_errors' => false,
            'form_params' => $params,
        ]);

        $content = $response->getBody();

        if (!empty($content)) {
            return json_decode($content, true);
        }

        return ['state' => -1, 'message' => 'api result empty'];
    }

    public static function httpGet($scheme = '', array $params = [])
    {
        $client = new Client([
            'base_uri' => Yii::$app->params['api_base_uri'],
        ]);

        $response = $client->get($scheme, [
            'http_errors' => false,
            'form_params' => $params,
        ]);

        $content = $response->getBody();

        if (!empty($content)) {
            return json_decode($content, true);
        }

        return ['code' => -1, 'message' => 'rsa encrypt error'];
    }

    public static function is_mobile( $text ) {
    $search = '/^0?(13|14|15|17|18|19|16)[0-9]{9}$/';
    if ( preg_match( $search, $text ) ) {
            return  true ;
        } else {
            return false ;
    }
}

    public static function generate_verify_code($length = 6,$chars = '0123456789'){
        return self::generate_rand_str($length,$chars);
    }

    public static function generate_rand_str( $length = 6 ,$chars = 'abcdefghijklmnopqrstuvwxyz0123456789') {
        $rand_str = '';
        for ( $i = 0; $i < $length; $i++ )
        {
            $rand_str .= $chars[ mt_rand(0, strlen($chars) - 1) ];
        }
        return $rand_str;
    }

    //验证手机号是否在三分钟内发送过验证码
    public static function getPhoneSmsCodeAndCheckFrequently($phone_num,$act){
        $tmp_get =  RedisCommon::Instance()->getTelephoneVerifyCode($phone_num,$act);
        $key =$phone_num.'_'.$act;
        $ttl = Factory::Redis()->ttl($key);

        if(!empty($tmp_get) && $ttl <= TEL_CODE_EXPIRE_TIME && $ttl > (TEL_CODE_EXPIRE_TIME-ONE_MINITE_SECONDS)){
            throw new ErrorException(Yii::$app->params['codeMsg']['codeFrequently'], Yii::$app->params['ApiCode']['codeFrequently']);
        }
        $code = empty($tmp_get) ? self::generate_verify_code() : $tmp_get;
        return $code;
    }

    public  static function send_msg($tel,$msg,$type=0,$platform_id=''){
        $url = Yii::$app->params['send_sms'];
        $sign = md5($tel.$msg.$type.SENDSMSKEY);
        if(empty($msg)){
            return -3;
        }
        $params = array('tel'=>$tel,'msg'=>$msg,'type'=>$type,'sign'=>$sign);
        if(!empty($platform_id)){
            $params['from'] = 'gaming';
        }
        $resp_str = self::curl($url, $params);
        if(!$resp_str){
            return -2;
        }

        $resArr  = json_decode($resp_str,true);
        if(isset($resArr['code']) && $resArr['code'] == 0){
            return 0;
        }
        return -1;
    }

    public static function  myTrim($str)
    {
         $search = array(" ","　","\n","\r","\t");
         $replace = array("","","","","");
         return str_replace($search, $replace, $str);
    }

    public static function orderId($prefix) {
        if (empty($prefix)) {
            throw new InvalidValueException("请指定交易单号前缀字符串");
        }
            list($usec, $sec) = explode(" ", microtime());
            $mt = substr($usec, 2, 6);
            $randNum = mt_rand(100,999);
            $orderSn = chr(date('Y') - 1951) . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5)
              . $mt . sprintf('%03d', $randNum);
            return $prefix.$orderSn;

    }

    public static function des_encrypt($str, $key)
    {
        /* Open module, and create IV */
        $td = mcrypt_module_open('des', '', 'ecb', '');
        //$td = mcrypt_module_open(MCRYPT_DES, '', MCRYPT_MODE_CBC, '');
        //$td = mcrypt_module_open('des', '', 'cbc', ''); 
        $key = substr($key, 0, mcrypt_enc_get_key_size($td));
        $iv_size = mcrypt_enc_get_iv_size($td);
        $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
        /* Initialize encryption handle */
        if (mcrypt_generic_init($td, $key, $iv) === -1) {
            return FALSE;
        }
        /* Encrypt data */
        $c_t = mcrypt_generic($td, $str);
        /* Clean up */
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);
        return $c_t;
    }

    public static function httpBulidQuery($params)
    {
        return implode("&",array_map(function ($k, $v) {
            return "{$k}={$v}";
        }, array_keys($params), $params));
    }
}